using System;
using System.Reflection;
using System.Xml;
using System.Xml.Serialization;

namespace SolarWinds.Updates
{
    public class VersionCheck
    {
     
        private static VersionCheck _instance;
        private Version mVersion;
        private String xmlVersionFile = "http://www.file-finder.de/version.xml";

        /*
         *  <Singstar>
         *      <currentEditorVersion>1.0</currentEditorVersion>
         *      <editorChanges></editorChanges>
         *      <currentGameVersion>1.0</currentEditorVersion>
         *      <gameChanges></gameChanges>
         *  </Singstar>
         */

        protected VersionCheck()
        {
            Initialize();
        }

        public static VersionCheck Instance()
        {
            if (_instance == null)
            {
                _instance = new VersionCheck();
            }
            return _instance;
        }

        private void Initialize()
        {
            ReadXMLFile();
        }

        public void ReadXMLFile()
        {
            var xs = new XmlSerializer(typeof(System.Version));
            var xmlTextReader = new XmlTextReader(xmlVersionFile);

            try
            {
                xs.CanDeserialize(xmlTextReader);
                mVersion = (Version) xs.Deserialize(xmlTextReader);
            }
            catch (Exception)
            {
                Console.WriteLine("XML Version konnte nicht deserialized werden");
            }
        }

        public String NewestEditorVersion()
        {
            return mVersion.EditorVersion;
        }

        public String NewestGameVersion()
        {
            return mVersion.GameVersion;
        }

        public String CurrentEditorVersion()
        {
            return Assembly.Load("Editor").GetName().Version.ToString();
        }

        public String CurrentGameVersion()
        {
            return Assembly.Load("Core").GetName().Version.ToString();
        }

        public Boolean NewVersionAvailable()
        {
            if(!CurrentGameVersion().Equals(NewestGameVersion()))
            {
                return true;
            }
            if (!CurrentEditorVersion().Equals(NewestEditorVersion()))
            {
                return true;
            }
            return false;
        }
    }
}